<template>
  <div>
    <n-tabs v-model:value="tabValue" justify-content="start" type="line">
      <n-tab-pane name="list" tab="文章列表">
        <!-- v-for这里的括号写错了 -->
        <div v-for="(ii,index) in blogList" style="margin-bottom:15px">
          <n-card :title="ii.title">
            {{ii.content}}
            <template #footer>
              <n-space align="center">
                <div>
                  发布时间：{{ii.create_time}}
                </div>
                <n-button @click="toUpdate(ii)">修改</n-button>
                <n-button @click="toDelete(ii)">删除</n-button>

              </n-space>
            </template>
          </n-card>
        </div>
        <n-space>
          <div @click=" toPage(Number)" v-for="Number in pageInfo.pageCount">
            <div :style="'color:'+(Number == pageInfo.page? 'pink' : '')">{{Number}}</div>

          </div>
        </n-space>
      </n-tab-pane>
      <n-tab-pane name="add" tab="添加文章">
        <n-form>
          <n-form-item label="标题">
            <n-input v-model:value="addArticle.title" placeholder="请输入标题" />
          </n-form-item>
          <n-form-item label="文章分类">
            <n-select v-model:value="addArticle.categoryId" :options="categoryOptions" />

          </n-form-item>


          <n-form-item label="内容">
            <rich-text-editor v-model="addArticle.content"></rich-text-editor>
          </n-form-item>
          <n-form-item label="">
            <n-button @click="add">提交</n-button>
          </n-form-item>
        </n-form>
      </n-tab-pane>

      <n-tab-pane name="update" tab="修改">
        <n-form>
          <n-form-item label="标题">
            <n-input v-model:value="updateArticle.title" placeholder="请输入标题" />
          </n-form-item>
          <n-form-item label="文章分类">
            <n-select v-model:value="updateArticle.categoryId" :options="categoryOptions" />

          </n-form-item>


          <n-form-item label="内容">
            <rich-text-editor v-model="updateArticle.content"></rich-text-editor>
          </n-form-item>
          <n-form-item label="">
            <n-button @click="update">提交</n-button>
          </n-form-item>
        </n-form>
      </n-tab-pane>
    </n-tabs>

    {{addArticle.content}}

  </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted } from 'vue'
import { AdminStore } from '../../stores/AdminStore'  //1.引入
import { useRouter, useRoute } from 'vue-router'; //路由
import RichTextEditor from "../../components/RichTextEditor.vue"

const router = useRouter()
const route = useRoute()
const dialog = inject("dialog")

const message = inject("message")  //axiosTool 是我provide定义的名字
const axios = inject("axiosTool")  //axiosTool 是我provide定义的名字
const adminStore = AdminStore(); //2.实例化

const addArticle = reactive({
  title: "",
  content: "",
  categoryId: 0
})


const updateArticle = reactive({
  id: 0,
  title: "",
  content: "",
  categoryId: 0
})
const categoryOptions = ref([])
const blogList = ref([])

const tabValue = ref("list")
const pageInfo = reactive({
  page: 1,
  pageSize: 3,
  pageCount: 0,
  count: 0
})



onMounted(() => {
  loadBlogs()
  loadCategorys()
})
// 获取分类
const loadCategorys = async () => {
  let res = await axios.get("/categorty/list")
  // map（）可以把对象，转换成[key,vaule]的数组形式
  categoryOptions.value = res.data.rows.map((i) => {
    return {
      label: i.name,
      value: i.id
    }
  })
}


// 获取博客
const loadBlogs = async () => {
  let res = await axios.get(`/blog/search?page=${pageInfo.page}&pageSize=${pageInfo.pageSize}`)
  let temp_rows = res.data.data.rows;
  for (let jj of temp_rows) {
    jj.content += "..."
    let d = new Date(jj.create_time)
    jj.create_time = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
  }
  blogList.value = temp_rows;
  pageInfo.count = res.data.data.count
  // parseInt向下取整，就是不算小数点，  ，%是取余数
  pageInfo.pageCount = parseInt(pageInfo.count / pageInfo.pageSize) + (pageInfo.count % pageInfo.pageSize > 0 ? 1 : 0)

}
const add = async () => {
  // 提交的内容要和后端接受的变量一样
  let res = await axios.post("/blog/add", addArticle)
  //  { headers: { token: adminStore.token } }
  if (res.data.code == 200) {
    message.info(res.data.msg)
  } else {
    sage.error(res.data.msg)
  }
}



const toPage = async (Number) => {
  pageInfo.page = Number
  loadBlogs();
}
const toUpdate = async (ii) => {
  tabValue.value = "update"
  let res = await axios.get("/blog/detail?id=" + ii.id)
  console.log(res);
  updateArticle.id = res.data.rows[0].id;
  updateArticle.title = res.data.rows[0].title;

  updateArticle.content = res.data.rows[0].content;
  updateArticle.categoryId = res.data.rows[0].category_id;

}

const update = async () => {
  // 提交的内容要和后端接受的变量一样
  let res = await axios.put("/blog/_token/update", updateArticle)
  //  { headers: { token: adminStore.token } }
  if (res.data.code == 200) {
    message.info(res.data.msg)
    tabValue.value = "list"
    loadBlogs();
  } else {
    sage.error(res.data.msg)
  }

}

const toDelete = async (ii) => {
  dialog.warning({
    title: '警告',
    content: '是否要删除',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      let res = await axios.delete("/blog/_token/delete?id=" + ii.id)
      if (res.data.code == 200) {
        loadBlogs()
        message.info(res.data.msg)

      } else {
        message.error(res.data.msg)

      }
    },
    onNegativeClick: () => {
    }
  })
}
</script>

<style lang="scss" scoped>
</style>